from django.conf import settings
from django.contrib.auth.backends import ModelBackend

import re

from users.constants import VERIFY_EMAIL_TOKEN_EXPIRES
from users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as serializer


# 自定义 用户登录 后端


def get_user_model_by_account(usernameORmobile):
    try:
        if re.match(r'^1[3-9]\d{9}$', usernameORmobile):
            # 手机号
            print(usernameORmobile)
            user = User.objects.get(mobile=usernameORmobile)
        else:
            # 用户名
            user = User.objects.get(username=usernameORmobile)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobilBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        :param request:
        :param usernameORmobile:  用户名或手机号
        :param password: 密码
        :param kwargs:
        :return:
        """
        # 判断usernameORmobile 是用户名还是手机号
        user = get_user_model_by_account(username)
        # 校验用户
        if user and user.check_password(password):
            # 返回user
            return user
        else:
            return None


# 生成邮箱验证链接
def generate_verify_email_url(user: User) -> str:
    """
    邮箱验证 生成几激活链接
    :param user: 用户
    :return:
    """
    s = serializer(settings.SECRET_KEY, VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {"user_id": user.id, "email": user.email}
    token = s.dumps(data)

    return settings.EMAIL_VERIFY_URL + "?token=" + token.decode()


# 验证邮箱链接
def check_verify_email_url(token: str) -> User:
    s = serializer(settings.SECRET_KEY, VERIFY_EMAIL_TOKEN_EXPIRES)
    data = s.loads(token)
    if not data:
        return None
    user_id = data.get("user_id")
    email = data.get("email")
    try:
        user = User.objects.get(id=user_id, email=email)
    except Exception as e:
        return None
    else:
        return user
